package com.wangyadong.hobby.schedule.jobtask.javasync.semphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2019/1/2219:41
 **/
public class SemaphoreExample3 {

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);

        Thread t1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " in ");
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + " get the lock");
                TimeUnit.SECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
                System.out.println(Thread.currentThread().getName() + " RELEASE ");
            }
            System.out.println(Thread.currentThread().getName() + " finsh ");
        });
        t1.start();
        //////////////////////////////////////// ////////////////////////////////////////
        TimeUnit.MILLISECONDS.sleep(500);
        //////////////////////////////////////// ////////////////////////////////////////
        Thread t2 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " in ");
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + " get the lock");
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
                System.out.println(Thread.currentThread().getName() + " RELEASE ");
            }
            System.out.println(Thread.currentThread().getName() + " finsh ");
        });
        t2.start();

        t2.interrupt();
    }
}
